# subscriber.py

import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class SimpleSubscriber(Node):
    def __init__(self):
        # 初始化节点
        super().__init__('simple_subscriber')
        
        # 订阅 'simple_topic' 话题
        self.subscription = self.create_subscription(
            String,  # 消息类型
            'sub_test_topic',  # 订阅的主题名称
            self.listener_callback,  # 回调函数
            10  # 队列大小
        )
        self.subscription  # 防止取消订阅

    def listener_callback(self, msg):
        # 回调函数，在接收到消息时执行
        self.get_logger().info(f'Received message: {msg.data}')

def main(args=None):
    rclpy.init(args=args)  # 初始化 ROS2 客户端库
    node = SimpleSubscriber()  # 创建订阅者节点

    # 持续运行节点
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass

    # 清理资源
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()
